// $Id$
package lime.workflow.view;

import java.util.HashMap;
import java.util.Map;

import lime.Activator;
import lime.model.Workitem;
import lime.application.preference.WorkflowMonitorPreferencePage;

import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

public class WorkitemColorer {

	/**
	 * Map with colors that correspond to the different runtime states of the
	 * work item.
	 */
	private Map<String, Color> stateColorMap;

	/** Default color. */
	private Color defaultColor;

	/** Preference store that holds all color preferences. */
	IPreferenceStore store;

	public WorkitemColorer() {
		store = Activator.getDefault().getPreferenceStore();
		stateColorMap = new HashMap<String, Color>();
		load();
	}

	private void load() {

		Display display = Activator.getDefault().getWorkbench().getDisplay();

		// Set the default color to white
		defaultColor = new Color(display, new RGB(255, 255, 255));

		RGB dormant = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_DORMANT_COLOR);
		RGB acquired = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_ACQUIRED_COLOR);
		RGB finished = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_FINISHED_COLOR);
		RGB paused = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_PAUSED_COLOR);
		RGB dpaused = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_DPAUSED_COLOR);
		RGB apaused = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_APAUSED_COLOR);
		RGB ppaused = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_PPAUSED_COLOR);
		RGB faulted = PreferenceConverter.getColor(store, WorkflowMonitorPreferencePage.WORKITEM_STATE_FAULTED_COLOR);

		stateColorMap.put("0", new Color(display, dormant));
		stateColorMap.put("1", new Color(display, acquired));
		stateColorMap.put("2", new Color(display, finished));
		stateColorMap.put("3", new Color(display, paused));
		stateColorMap.put("4", new Color(display, dpaused));
		stateColorMap.put("5", new Color(display, apaused));
		stateColorMap.put("6", new Color(display, ppaused));
		stateColorMap.put("7", new Color(display, faulted));
	}

	public void reload() {
		load();
	}

	public Color getColor(Workitem workitem) {
		String state = workitem.getRuntimeState();
		if (stateColorMap.containsKey(state)) {
			return stateColorMap.get(state);
		} else {
			return defaultColor;
		}
	}

}